package sistemadeproyectos;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.ImageIcon;
import java.awt.Image;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.net.*;
import java.io.*;
import java.util.*;

public class ImagenVentana extends javax.swing.JDialog {

    public String URLImagen = "";
    public String texto;
    public int alto;
    public int ancho;
    public boolean aceptar = false;
    private Equipo equipoActual;
    private Usuario usuarioActivo;
    private Socket conexion;
    private ObjectInputStream entrada;
    private ObjectOutputStream salida;
    
    /** Creates new form ImagenVentana */
    public ImagenVentana(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    private void limpiar_socket() {
        try { 
          (this.entrada).close();
          (this.salida).close();
          (this.conexion).close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jlblImagen = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jtxtTexto = new javax.swing.JTextField();
        jtxtURLImagen = new javax.swing.JTextField();
        jbtnExaminar = new javax.swing.JButton();
        jbtnAceptar = new javax.swing.JButton();
        jbtnCancelar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jtxtAlto = new javax.swing.JTextField();
        jtxtAncho = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(ImagenVentana.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jlblImagen.setText(resourceMap.getString("jlblImagen.text")); // NOI18N
        jlblImagen.setToolTipText(resourceMap.getString("jlblImagen.toolTipText")); // NOI18N
        jlblImagen.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jlblImagen.setName("jlblImagen"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jtxtTexto.setText(resourceMap.getString("jtxtTexto.text")); // NOI18N
        jtxtTexto.setName("jtxtTexto"); // NOI18N

        jtxtURLImagen.setEditable(false);
        jtxtURLImagen.setText(resourceMap.getString("jtxtURLImagen.text")); // NOI18N
        jtxtURLImagen.setName("jtxtURLImagen"); // NOI18N

        jbtnExaminar.setText(resourceMap.getString("jbtnExaminar.text")); // NOI18N
        jbtnExaminar.setToolTipText(resourceMap.getString("jbtnExaminar.toolTipText")); // NOI18N
        jbtnExaminar.setName("jbtnExaminar"); // NOI18N
        jbtnExaminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExaminarActionPerformed(evt);
            }
        });

        jbtnAceptar.setText(resourceMap.getString("jbtnAceptar.text")); // NOI18N
        jbtnAceptar.setName("jbtnAceptar"); // NOI18N
        jbtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAceptarActionPerformed(evt);
            }
        });

        jbtnCancelar.setText(resourceMap.getString("jbtnCancelar.text")); // NOI18N
        jbtnCancelar.setName("jbtnCancelar"); // NOI18N
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setFont(resourceMap.getFont("jLabel5.font")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jtxtAlto.setText(resourceMap.getString("jtxtAlto.text")); // NOI18N
        jtxtAlto.setName("jtxtAlto"); // NOI18N

        jtxtAncho.setText(resourceMap.getString("jtxtAncho.text")); // NOI18N
        jtxtAncho.setName("jtxtAncho"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addComponent(jbtnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 126, Short.MAX_VALUE)
                        .addComponent(jbtnCancelar)
                        .addGap(83, 83, 83))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jtxtURLImagen, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE))
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(40, 40, 40)
                                .addComponent(jtxtAlto, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 126, Short.MAX_VALUE)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jtxtAncho, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addComponent(jbtnExaminar)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(105, 105, 105)
                        .addComponent(jtxtTexto, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel1)
                        .addGap(37, 37, 37)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jtxtTexto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jtxtURLImagen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jbtnExaminar))
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jtxtAlto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)
                            .addComponent(jtxtAncho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jbtnCancelar)
                            .addComponent(jbtnAceptar)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void setConexion(){
        ServersConf rutas = new ServersConf();
        try {
            //Se crea la conexión con el serivor de Repositorio
            this.conexion = new Socket (rutas.getIPRepositorio(), rutas.getPuertoRepositorio());
            this.entrada = new ObjectInputStream ((this.conexion).getInputStream());
            this.salida = new ObjectOutputStream ((this.conexion).getOutputStream());
            this.salida.writeObject(this.usuarioActivo.getUsuario());
            this.salida.writeObject(this.equipoActual.getIdEquipo());
            ArrayList<String> recibido = (ArrayList<String>)(this.entrada).readObject();
        }
        catch (IOException e) { 
            JOptionPane.showMessageDialog(this, "Error al establecer conexion con servidor.", 
                "Error en Conexion", JOptionPane.ERROR_MESSAGE);
            limpiar_socket();
            e.printStackTrace();
            this.dispose();
        }
        catch(ClassNotFoundException cnfe){
            cnfe.printStackTrace();
        }
    }
    
    public void setTexto(String elTexto){
        this.jtxtTexto.setText(elTexto);
    }
    
    public void setURL(String laURL){
        this.jtxtURLImagen.setText(laURL);
        this.URLImagen = laURL;
        
        try{
            (this.salida).writeObject("imagen");
            (this.salida).writeObject(laURL);
            (this.salida).writeObject(jlblImagen.getWidth()+"");
            (this.salida).writeObject(jlblImagen.getHeight()+"");
            ImageIcon resultImagen = (ImageIcon)(this.entrada).readObject();
            jlblImagen.setIcon(resultImagen);
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
        catch(ClassNotFoundException cnfe){
            cnfe.printStackTrace();
        }
    }
    
    public void setAncho(String elAncho){
        this.jtxtAncho.setText(elAncho);
    }
    
    public void setAlto(String elAlto){
        this.jtxtAlto.setText(elAlto);
    }
    
    public void setEquipo(Equipo elEquipo){
        this.equipoActual = elEquipo;
    }
    
    public void setUsuario(Usuario elUsuario){
        this.usuarioActivo = elUsuario;
    }
    
    private ImageIcon ajustarImagen(String ico, int alto, int ancho) {
        ImageIcon tmpIconAux = new ImageIcon(ico);
        //Escalar Imagen
        ImageIcon tmpIcon = new ImageIcon(tmpIconAux.getImage().getScaledInstance(ancho, alto, Image.SCALE_DEFAULT));
        return tmpIcon;
    }
    
    private void jbtnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExaminarActionPerformed
        // TODO add your handling code here:
        JFrame mainFrame = SistemadeproyectosApp.getApplication().getMainFrame();
        SeleccionaImagen selector = new SeleccionaImagen(mainFrame, true, this.equipoActual, this.usuarioActivo);
        selector.setVisible(true);
        String retorno = selector.pathResultado;
        if(retorno != null){
            jlblImagen.setIcon(new ImageIcon(selector.imagenResultado.getImage().getScaledInstance(jlblImagen.getWidth(), jlblImagen.getHeight(), Image.SCALE_DEFAULT)));
            URLImagen = retorno;
            jtxtURLImagen.setText(retorno);
        }
        
        /*
        JFileChooser fileChooser = new JFileChooser();   
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos de imagen: JPG & GIF", "jpg", "gif");
        fileChooser.setFileFilter(filter);
        fileChooser.setAcceptAllFileFilterUsed(false);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION ){
            String name = fileChooser.getSelectedFile().getPath();
            jlblImagen.setIcon(ajustarImagen(name, jlblImagen.getHeight(), jlblImagen.getWidth()));
            URLImagen = name;
            jtxtURLImagen.setText(name);
        }*/
    }//GEN-LAST:event_jbtnExaminarActionPerformed

    private void jbtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAceptarActionPerformed
        // TODO add your handling code here:
        if (this.URLImagen.equals("") == false){
            this.aceptar = true;
            this.alto = Integer.parseInt(jtxtAlto.getText());
            this.ancho = Integer.parseInt(jtxtAncho.getText());
            this.texto = jtxtTexto.getText();
            try{
                (this.salida).writeObject("salir");
            }
            catch(IOException ioe){}
            limpiar_socket();
            this.dispose();
        }
        else{
            JOptionPane.showMessageDialog(null, "Error: la imagen no ha sido establecida", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jbtnAceptarActionPerformed

    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        // TODO add your handling code here:
        try{
            (this.salida).writeObject("salir");
        }
        catch(IOException ioe){}
        limpiar_socket();
        this.dispose();
    }//GEN-LAST:event_jbtnCancelarActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        try{
            (this.salida).writeObject("salir");
        }
        catch(IOException ioe){}
        limpiar_socket();
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ImagenVentana dialog = new ImagenVentana(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jbtnAceptar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnExaminar;
    private javax.swing.JLabel jlblImagen;
    private javax.swing.JTextField jtxtAlto;
    private javax.swing.JTextField jtxtAncho;
    private javax.swing.JTextField jtxtTexto;
    private javax.swing.JTextField jtxtURLImagen;
    // End of variables declaration//GEN-END:variables
}
